import { ref, type App, type Ref } from 'vue'
import { defineStore } from 'pinia'
import type { Section } from '@/common/models/recommend-result';
import type { Item } from 'muuri';
import CardContainer from '@/views/briefinfo/components/CardContainer.vue';

// 模块信息
interface SectionInfo {
  // 模块数据
  section: Section;
  // 模块所在的卡片应用
  cardApp: App;
  // 模块所在的卡片网格项
  cardGridItem: Item;
  // 模块所在的卡片组件实例
  cardVm: InstanceType<typeof CardContainer>;
}

export const usePanelStore = defineStore('panel', () => {
  const currentPanel: Ref<{ id: string, title: string } | null> = ref(null);

  const currentSections: Ref<Section[]> = ref([]);

  const sectionInfoMap: Ref<Map<string, SectionInfo>> = ref(new Map());

  const selectSection = ref<Section | null>(null);

  const currentRecommendQustions: Ref<string[]> = ref([]);

  function setPanel(payload: { id: string, title: string } | null) {
    currentPanel.value = payload
  }

  function setSections(payload: Section[]) {
    currentSections.value = payload
  }

  function setSelectSection(payload: Section | null) {
    selectSection.value = payload
  }

  function setRecommendQuestions(payload: string[]) {
    currentRecommendQustions.value = payload
  }

  function addSectionInfo(section: Section, cardApp: App, cardVm: InstanceType<typeof CardContainer>, cardGridItem: Item) {
    sectionInfoMap.value.set(section.id, { section, cardApp, cardGridItem, cardVm })
    currentSections.value = [...currentSections.value, section]
  }

  function removeSectionInfo(sectionId: string) {
    const sectionInfo = sectionInfoMap.value.get(sectionId)
    if (sectionInfo) {
      const grid = sectionInfo.cardGridItem.getGrid()
      grid?.remove([sectionInfo.cardGridItem], { removeElements: true })
      sectionInfo.cardApp.unmount()
      currentSections.value = currentSections.value.filter(section => section.id !== sectionId)
    }
    sectionInfoMap.value.delete(sectionId)
  }

  function getSectionInfo(sectionId: string): SectionInfo | undefined {
    return sectionInfoMap.value.get(sectionId)
  }

  function clearSectionInfo() {
    sectionInfoMap.value.forEach(sectionInfo => {
      sectionInfo.cardGridItem.getGrid()?.remove([sectionInfo.cardGridItem], { removeElements: true })
      sectionInfo.cardApp.unmount()
    })
    currentSections.value = []
    selectSection.value = null
    sectionInfoMap.value.clear()
  }

  return { currentPanel, setPanel, currentSections, setSections, selectSection, setSelectSection, currentRecommendQustions, setRecommendQuestions, addSectionInfo, removeSectionInfo, getSectionInfo, clearSectionInfo }
})
